package com.pri.chat.activity;

import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.base.TcWebActivity;
import com.pri.chat.model.RegModel;
import com.pri.chat.utils.Auth;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.PictureChoiceUtil;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.view.ImageViewPlus;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.view.RxToast;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：完善资料
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/15
 */
public class CompleteMaterialActivity extends BaseActivity {
    private static final String TAG = "RegActivity";
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.cb_xieyi)
    CheckBox cbXieyi;
    @BindView(R.id.tv_xieyi)
    TextView tvXieyi;
    @BindView(R.id.tv_ys)
    TextView tvYs;
    @BindView(R.id.tv_reg)
    TextView tvReg;
    @BindView(R.id.iv_tou)
    ImageViewPlus ivTou;
    @BindView(R.id.iv_woman)
    ImageView ivWoman;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_yqm)
    EditText et_yqm;
    @BindView(R.id.ll_sex_man)
    LinearLayout layoutSexMan;
    @BindView(R.id.ll_sex_woman)
    LinearLayout layoutSexWoman;
    @BindView(R.id.tv_city)
    TextView tvCity;


    @BindView(R.id.title)
    TextView title;


    private UploadManager uploadManager = new UploadManager();
    private String mCodeId;//验证码ID
    private RegModel regModel = new RegModel();//注册上传参数
    private int sex = -1;

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_complete_material_layout;
    }


    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {

    }

    private String locationPath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    locationPath = PictureSelector.obtainMultipleResult(data).get(0).getPath();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        locationPath = PictureSelector.obtainMultipleResult(data).get(0).getAndroidQToPath();
                    }
                    RequestOptions options = new RequestOptions()
                            .placeholder(R.mipmap.ic_paizhao_img)//图片加载出来前，显示的图片
                            .fallback(R.mipmap.ic_paizhao_img) //url为空的时候,显示的图片
                            .error(R.mipmap.ic_paizhao_img);//图片加载失败后，显示的图片
                    Glide.with(mContext).load(locationPath).apply(options).into(ivTou);
                }
                break;
        }
    }

    private void uploadImg(String data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "img_" + sdf.format(new Date());
        String token = "ayjstx";
        uploadManager.put(data, key, Auth.create(HttpMethods.ACCESS_KEY, HttpMethods.SECRET_KEY).uploadToken(token),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            Log.i("qiniu", "Upload Success");
                            Log.d(TAG, "complete: " + HttpMethods.QN_PATH + key);
                            regModel.setHeadPic(HttpMethods.QN_PATH + key);
                            login();
                        } else {
                            Log.i("qiniu", "Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);
    }

    @OnClick({R.id.tv_xieyi, R.id.tv_ys, R.id.tv_reg, R.id.iv_tou, R.id.ll_sex_man, R.id.ll_sex_woman,
            R.id.ll_select_city})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_tou:
                PictureChoiceUtil.getInstance().choiceTouPic(this, new ArrayList<>());
                break;
            case R.id.tv_xieyi:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", HttpMethods.BASE_URL + "p/front_editorHtmlShow.html?code=yonghuxieyiCode");
                startActivity(intent);
                break;
            case R.id.tv_ys:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title", "隐私协议");
                intent.putExtra("url", HttpMethods.BASE_URL + "p/front_editorHtmlShow.html?code=yinsixieyiCode");
                startActivity(intent);
                break;
            case R.id.tv_reg:
                if (isNull(etName)) {
                    RxToast.normal(etName.getHint().toString());
                    return;
                }
                if (isNull(etPwd)) {
                    RxToast.normal(etPwd.getHint().toString());
                    return;
                }

                if (!cbXieyi.isChecked()) {
                    RxToast.normal("请阅读并勾选用户协议");
                    return;
                } else {
                    if (StringUtils.isEmpty(locationPath)) {
                        RxToast.normal("请上传图像！");
                        return;
                    }
                    showProgressDialog();
                    uploadImg(locationPath);
                }
                break;

            case R.id.ll_sex_man:
                sex = 0;
                layoutSexMan.setSelected(true);
                layoutSexWoman.setSelected(false);
                break;
            case R.id.ll_sex_woman:
                sex = 1;
                layoutSexMan.setSelected(false);
                layoutSexWoman.setSelected(true);
                break;
            case R.id.ll_select_city:
                RxToast.normal("选择城市");
                break;
        }
    }


    private void login() {
        String deviceId = RxDeviceTool.getIMEI(this);
        if (StringUtils.isEmpty(deviceId)) {
            RxToast.normal("没有获取到设备ID，无法注册！");
            return;
        }
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            dismissProgressDialog();
            Log.d(TAG, "onNext: " + baseBean.toString());
            RxToast.normal("注册成功");
            finish();
        };
        if (sex == -1) {
            RxToast.normal("请选择性别！");
            return;
        }
        if (sex == 0) {
            regModel.setSex("男");
        } else {
            regModel.setSex("女");
        }

        if (regModel.getHeadPic() == null || "".equals(regModel.getHeadPic())) {
            RxToast.normal("请上传图像！");
            return;
        }
//        regModel.setCode(code);
//        regModel.setMobile(mobile);
        regModel.setNcName(getString(etName));
        regModel.setSendId(mCodeId);
        regModel.setPassword(getString(etPwd));
        regModel.setDeviceId(deviceId);
        regModel.setInvitedUserCode(et_yqm.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(regModel));
        HttpMethods.getInstance().register(new ProgressSubscriber<>(onNextListener, this, false), requestBody);

    }


}
